#!/bin/bash

# 获取最新版
# Url=$(curl -Ls https://github.com/prometheus/prometheus/releases |awk -F'[ "]+' '/download.*prometheus-.*.linux-amd64.tar.gz/{print "https://github.com"$4 }' |head -n 1)
# curl -Lso /tmp/prometheus.tar.gz $Url

# 软件安装目录
INSTALL_DIR=/usr/local/prometheus

function _install () {
    # 下载软件
    VERSION=2.12.0
    if [ -d "$INSTALL_DIR" ]; then
        echo "[INFO] prometheus 已经安装."
        exit 1
    fi
    curl -L --progress -o /tmp/prometheus-${VERSION}.linux-amd64.tar.gz http://dl.hc-yun.com/soft/monitor/prometheus-${VERSION}.linux-amd64.tar.gz

    # 解压 配置
    [ -d "$INSTALL_DIR" ] && mv $INSTALL_DIR ${INSTALL_DIR}-$(date +%Y%m%d%H%M%S)
    tar xf /tmp/prometheus-${VERSION}.linux-amd64.tar.gz
    mv prometheus-${VERSION}.linux-amd64 $INSTALL_DIR

    # 创建服务
    cat > /usr/lib/systemd/system/prometheus.service <<-EOF
	[Unit]
	Description=prometheus server daemon
	After=network.target

	[Service]
	Restart=on-failure
	ExecStart=${INSTALL_DIR}/prometheus --config.file=${INSTALL_DIR}/prometheus.yml
	ExecReload=/bin/kill -HUP \$MAINPID

	[Install]
	WantedBy=multi-user.target
	EOF

    # 防火墙
    firewall-cmd --add-port=9090/tcp --permanent
    firewall-cmd --reload

    # 启动服务跟随系统启动
    systemctl daemon-reload
    systemctl enable prometheus
    systemctl restart prometheus
    systemctl status prometheus

    echo -e "\n\tWebUi:  http://$(hostname -I|sed 's# ##g'):9090\n"
}

function _uninstall () {
    # 停止服务 禁用开机自启动 删除服务
    systemctl stop prometheus
    systemctl disable prometheus
    if [ -f "$INSTALL_DIR/prometheus.yml" ]; then
        mv $INSTALL_DIR/prometheus.yml /usr/local/etc/prometheus-$(date +%Y%m%d%H%M%S).yml
    fi
    rm -f /usr/lib/systemd/system/prometheus.service
    rm -rf $INSTALL_DIR   
}

function _usage () {
    echo ""
    echo "Usage $0 {install|uninstall}"
    echo ""
}

case $1 in
  install)
    _install
    ;;
  uninstall)
    _uninstall
    ;;
  *)
    _usage
    ;;
esac
